<template>
  <view class="top-bar">
    <view class="top-left" @click="onClick">
      <img src="@/assets/img/logo.png" />
      <text>{{ props.title }}</text>
    </view>
    <view class="top-middle" style="text-align: center">
      <img src="@/assets/img/phone.png" />
      <text class="time-range">19969666288</text>
    </view>
    <view class="top-right" style="text-align: right">
      <text class="date">{{ currentDate }}</text>
      <text class="date" style="margin-left: 40rpx">剩余柜门：{{ count }}</text>
    </view>
  </view>
</template>

<script setup lang="ts">
  import { getDeviceInfoToDc } from '@/api/comm'
  import { useNavigatePage } from '@/hooks/navigateTo'
  import { onShow } from '@dcloudio/uni-app'
  import { ref, onMounted, onUnmounted, nextTick } from 'vue'
  const currentDate = ref('')
  const props = defineProps({
    title: {
      type: String,
      default: '智能寄存柜',
    },
    deviceId: {
      type: String,
    },
  })
  const timer = ref<any>(null)
  const sygmTimer = ref<any>(null) // 新增定时器
  const count = ref(0)
  onMounted(() => {
    updateDate()
    timer.value = setInterval(updateDate, 1000)
    sygmFun()
    sygmTimer.value = setInterval(sygmFun, 30000) // 每30秒执行一次
  })
  const sygmFun = async () => {
    const result = await getDeviceInfoToDc(props.deviceId || '')
    if (result) {
      count.value = result.data
    }
  }
  onShow(() => {
    nextTick(() => {
      updateDate()
      timer.value = setInterval(updateDate, 1000)
      sygmFun()
      sygmTimer.value = setInterval(sygmFun, 30000) // 每30秒执行一次
    })
  })
  onUnmounted(() => {
    if (timer.value) clearInterval(timer.value)
    if (sygmTimer.value) clearInterval(sygmTimer.value) // 清理定时器
  })
  const formatDate = (date: any) => {
    const month = date.getMonth() + 1
    const day = date.getDate()
    const h = String(date.getHours()).padStart(2, '0')
    const m = String(date.getMinutes()).padStart(2, '0')
    const s = String(date.getSeconds()).padStart(2, '0')
    return {
      time: `${month}月${day}日   ${h}:${m}:${s}`,
      times: `${h}:${m}:${s}`,
    }
  }
  const updateDate = () => {
    const timeData = formatDate(new Date())
    currentDate.value = timeData.time
    if (timeData.times === '07:00:00' || timeData.times === '12:00:00' || timeData.times === '22:00:00') {
      onClick()
    }
  }
  const onClick = () => {
    location.reload()
  }
</script>

<style scoped lang="scss">
  .top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 40rpx 92rpx;
    font-size: 28rpx;
    background: #0065f2;
  }

  .top-left,
  .top-middle,
  .top-right {
    flex: 1;
    font-size: 48rpx;
    color: #ffffff;
  }
  .top-left,
  .top-middle {
    img {
      width: 60rpx;
      height: 60rpx;
      vertical-align: bottom;
      margin-right: 20rpx;
    }
  }
</style>
